<template>
  <view class="login">
    <view @click="backHome"  :style="{paddingTop: safeArea_top + 'px'}">
      <u-icon name="arrow-left" color="#000" size="22"></u-icon>
    </view>
    <view>
      <view class="h1"> 手机快捷登录 </view>
      <view class="p">未注册过的手机将自动创建账号</view>

      <view class="ipt">
        <input
          type="number"
          v-model="phone"
          placeholder="输入手机号"
          placeholder-style="color:rgba(153, 153, 153, 1)"
        />
      </view>

      <view class="ipt">
        <input type="number" v-model="code" placeholder="输入验证码" />
        <text @tap.stop="onMultClick(sendMsg)">{{ msg }}</text>
      </view>
      <view class="btn" @tap.stop="onMultClick(submit)"> 登录 </view>
    </view>

    <view class="other">
      <view v-if="false">其他登录方式</view>
      <image
        class="wx"
        src="../../static/icon/icon_wechat.png"
        mode=""
        @click="wxLogin"
        v-if="false"
      ></image>
      <view>
        <u-checkbox-group
          placement="row"
          v-model="treaty"
          style="display: flex; align-items: center"
        >
          <u-checkbox
            activeColor="#38987c"
            name="1"
            style="font-size: 20rpx"
          ></u-checkbox>
          <text>
            <text style="color: #333">登陆即同意</text>
            <text @tap.stop="topath('privacy')">《隐私政策》</text>
            <text style="color: #333">和</text>
            <text @click="topath('service')">《服务条款》</text>
          </text>
        </u-checkbox-group>
      </view>
    </view>
  </view>
</template>
<script>
var clear;
import { mapState, mapMutations } from "vuex";
export default {
  data() {
    return {
      treaty: ["1"],
      phone: "",
      code: "",
      msg: "获取验证码",
      is_ios: 0,
      isDev: false,
      logoUrl: "",
      wx_config: "",
      name: "",
      onClick: true,
	  safeArea_top: 0
    };
  },
  async onLoad() {
	const safeArea = uni.getStorageSync('safeArea')
	this.safeArea_top = safeArea.top
    uni.showLoading({
      title: "加载中",
    });
    // #ifdef H5
    if (window.location.origin.indexOf("http://localhost") === -1) {
      this.isDev = false;
    }
    // #endif
    // 获取code
    await this.$http.post("api/index/shareConfig").then((res) => {
      uni.hideLoading();
      const { is_ios, logo, name, wx_config } = res;
      this.wx_config = JSON.parse(wx_config);
      this.logoUrl = logo;
      this.name = name;
      if (uni.getSystemInfoSync().platform == "ios") {
        this.is_ios = is_ios;
      } else {
        this.is_ios = 1;
      }
      uni.setStorageSync("is_ios", this.is_ios);
    });
    // #ifdef H5
    console.log(this.wx_config);
    this.publicAppId = this.wx_config.wx_app_id;
    let obj = this.getCode();
    if (obj.code) {
      // 存在code 则code登录
      // alert(obj.code);
      uni.showLoading({
        title: "登录中...",
        mask: true,
      });
      this.wxCodeLogin(obj.code);
    } else {
      if (this.isDev) {
        return;
      }
    }
    // #endif
  },
  methods: {
    ...mapMutations(["setUserInfo"]),
    backHome() {
      uni.switchTab({ url: "/pages/my/my" });
    },
    getCode() {
      let redirect_uri = window.location.href;
      let arr = redirect_uri.split("?");
      let obj = {
        code: "",
      };
      if (arr.length > 1) {
        arr = arr[1];
        arr = arr.split("&");
        arr.forEach((item) => {
          let a = item.split("=");
          obj[a[0]] = a[1];
        });
      }
      return obj;
    },
    wxCodeLogin(code) {
      let obj = {
        code,
      };
      if (uni.getStorageSync("pid")) {
        obj.pid = Number(uni.getStorageSync("pid"));
      }
      if (uni.getStorageSync("tpid")) {
        obj.tpid = Number(uni.getStorageSync("tpid"));
      }
      this.$http.post("api/wechat/login", obj).then((res) => {
        uni.removeStorageSync("tpid");
        uni.removeStorageSync("pid");
        let { code, openid, token } = res;
        uni.setStorageSync("openid", openid);
        uni.hideLoading();
        if (code === 1) {
          // 未绑定手机
          uni.navigateTo({
            url: "/pages1/user/bindPhone",
          });
        } else {
          uni.setStorageSync("userInfo", {
            token,
          });
          uni.showToast({
            title: "登录成功",
            duration: 1500,
            success: () => {
              const needurl = uni.getStorageSync("need2url");
              if (!needurl) {
                uni.switchTab({
                  url: "/pages/index/index",
                });
              } else {
                uni.removeStorageSync("need2url");
                if (needurl.indexOf("user/login") > 0) {
                  uni.switchTab({
                    url: "/pages/index/index",
                  });
                } else {
                  window.location.href = needurl;
                }
              }
            },
          });
        }
      });
    },
    topath(e) {
      if (e == "privacy") {
        uni.navigateTo({
          url: "/bundle/pages/web/web?title=privacy",
        });
      } else {
        uni.navigateTo({
          url: "/bundle/pages/web/web?title=service",
        });
      }
    },
    // 发送验证码
    sendMsg() {
      if (this.readonly) {
        return;
      }
      if (!this.phone) {
        uni.showToast({
          title: "请输入手机号",
          icon: "none",
        });
        return;
      }
      if (!this.$base.phoneRegular.test(this.phone)) {
        uni.showToast({
          title: "手机号格式不正确",
          icon: "none",
        });
        return;
      }
      console.log("api/user/smsCode_bao");
      this.$http
        .post("api/user/smsCode_bao", {
          mobile: this.phone,
        })
        .then((res) => {
          this.getCodeState();
        });
    },
    //验证码按钮文字状态
    getCodeState() {
      clear && clearInterval(clear);
      const _this = this;
      this.readonly = true;
      this.msg = "60S";
      var s = 60;
      clear = setInterval(() => {
        s--;
        _this.msg = s + "S";
        if (s <= 0) {
          clearInterval(clear);
          _this.msg = "获取验证码";
          _this.readonly = false;
        }
      }, 1000);
    },
    //请求登录接口方法
    getApploginData(data) {
      ///api/user/wxLogin
      console.log(data);
      var that = this;
      //这边是前端自己去调微信用户信息的接口，根据接口需要请求，如果不需要前端去获取的话就交给后端，可省去次操作
      this.$http
        .post("api/user/wxLogin", {
          openid: data.openId,
          nickname: data.nickName,
          avatar: data.avatarUrl,
          unionid: data.unionId,
        })
        .then((res) => {
          if (res.code == 1) {
            console.log(data);
            //return
            uni.navigateTo({
              url: "/pages1/user/bindPhone?data=" + JSON.stringify(data),
            });
          } else {
            uni.setStorageSync("userInfo", {
              token: res.token,
            });
            uni.showToast({
              title: "登录成功",
              duration: 2000,
              success: () => {
                // setTimeout(() => {
                uni.switchTab({
                  url: "/pages/index/index",
                });
                // }, 1000);
              },
            });
          }
        });
    },

    h5_wxLogin() {
      // 微信授权
      console.log(this.wx_config.wx_app_id);
      let redirect_uri = window.location.href;
      window.location.href =
        `https://open.weixin.qq.com/connect/oauth2/authorize?appid=` +
        this.wx_config.oa_app_id +
        `&redirect_uri=${redirect_uri}&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect`;
    }, //
    submit() {
      console.log("this.treaty", this.treaty);
      console.log(this.$base);

      if (this.treaty.length == 0) {
        uni.$u.toast("请勾选同意协议！");
        return;
      }
      if (!this.phone) {
        uni.showToast({
          title: "请输入手机号",
          icon: "none",
        });
        return;
      }
      if (!this.$base.phoneRegular.test(this.phone)) {
        uni.showToast({
          title: "手机号格式不正确",
          icon: "none",
        });
        return;
      }
      if (!this.code) {
        uni.showToast({
          title: "请输入验证码",
          icon: "none",
        });
        return;
      }
      this.$http
        .post("api/user/login", {
          username: this.phone,
          sms_code: this.code,
          type: 2,
        })
        .then((res) => {
			console.log('login-res', res);
          uni.setStorageSync("userInfo", { token: res });
          uni.showToast({
            title: "登录成功",
            duration: 1500,
            success: () => {
              uni.switchTab({
                url: "/pages/my/my",
              });
            },
          });
        });
    },
  },
};
</script>
<style lang="scss" scoped>
.wx1 {
  width: 194rpx;
  height: 194rpx;
  display: block;
  margin: 20px auto 0 auto;
  border-radius: 50%;
}

.h1 {
  //text-align: center;
  margin-bottom: 50rpx;
  padding-top: 100rpx;
}

.h5-btn {
  height: 100rpx;
  background-color: #38987c;
  border-radius: 28rpx;
  display: flex;
  align-items: center;
  margin: 106rpx 30rpx 60rpx;
  justify-content: center;
  font-size: 36rpx;
  color: #ffffff;
}

.check {
  display: flex;
  justify-content: center;
  font-size: 24rpx;
  color: rgba(102, 102, 102, 1);

  text {
    color: #38987c;
  }
}

.login {
  height: 100vh;
  background-color: white;
  display: flex;
  flex-direction: column;
  padding: 56rpx 32rpx;

  .o {
    position: fixed;
    width: 692rpx;
    height: 692rpx;
    background-color: rgba(24, 181, 103, 0.1);
    top: 0rpx;
    right: -346rpx;
    z-index: 999;
    border-radius: 692rpx;
    margin-top: -346rpx;
  }

  .o1 {
    position: fixed;
    width: 880rpx;
    height: 880rpx;
    background-color: rgba(24, 181, 103, 0.05);
    top: 0;
    right: -440rpx;
    z-index: 999;
    border-radius: 50%;
    margin-top: -440rpx;
  }

  .h1 {
    color: rgba(41, 41, 41, 1);
    font-size: 40rpx;
    font-weight: bold;
    margin-top: 60rpx;
    position: relative;
    z-index: 999;
    // text-align: center;
  }

  .p {
    color: rgba(153, 153, 153, 1);
    font-size: 24rpx;
    margin-bottom: 60rpx;
    // text-align: center;
  }

  .ipt {
    display: flex;
    align-items: center;
    padding: 24rpx 0;
    border-bottom: 1rpx solid rgba(0, 0, 0, 0.06);
    margin-bottom: 30rpx;
    position: relative;

    input {
      font-size: 28rpx;
    }

    text {
      position: absolute;
      width: 5em;
      text-align: center;
      top: 50%;
      right: 0;
      transform: translateY(-50%);
      color: #38987c;
      font-size: 28rpx;
    }
  }

  .btn {
    margin: 64rpx 0 0;
    height: 88rpx;
    background-color: #38987c;
    border-radius: 28rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    color: white;
    font-size: 32rpx;
  }

  .other {
    position: fixed;
    width: 100%;
    bottom: 74rpx;
    left: 0;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;

    view:first-of-type {
      color: rgba(153, 153, 153, 1);
      font-size: 24rpx;
    }

    .wx {
      width: 96rpx;
      height: 96rpx;
      margin: 32rpx 0 80rpx 0;
    }

    view:last-of-type {
      font-size: 24rpx;
      color: rgba(102, 102, 102, 1);

      text {
        color: #38987c;
      }
    }
  }
}
</style>
